﻿import VTitle from '@/components/common/MainTitle.vue'
import VRefTable from './selectRefTable.vue'
import VSearchItem from './addSearch.vue'
import VAdd from './addFun.vue'
import VMenu from '@/components/SetMenu.vue'
export default {
  data () {
    return {
      titleName: '动态功能维护',
      // 左边部分
      filterText: '',
      filterFun: [],
      totalFun: [],
      currentFun: '',
      isEdit: false,
      operationType: 'add',
      showAddDialog: false,
      // 右边部分
      // 关联的元数据表
      totalRefTable: [],
      showRefDialog: false,
      labelFunWidth: '130px',
      // 新增查询条件的子条件时
      showAddSearchDialog: false,
      searchList: [],
      clickRow: 0,
      // 生成功能菜单部分
      menuDialog: false,
      functionObj: {},
      // 搜索的栏位
      searchColumnList: [],
      // 关联栏位的信息
      refTableColumns: [],
      totalRefColumns: [],
      // 所有的事件
      totalEvents: {
        events: [],
        row_events: []
      },
      // 事件的列表
      eventsList: [],
      // 行事件列表
      rowEventsList: [],
      ruleForm: {
        name: '',
        desc: '',
        action_auth: '',
        meta_uid: '',
        meta_name: '',
        // 普通事件
        events: [],
        // 行事件
        rowEvents: [],
        // 查询条件信息
        searchTable: [
          {
            search_id: '',
            search_desc: '',
            tips: '',
            is_required: false,
            memo: '',
            sort_num: 0,
            conditions: []
          }
        ],
        // 栏位表
        columTable: [
          {
            column_name: '',
            column_desc: '',
            max_length: '',
            tips: '',
            check_required: false,
            check_regex: '',
            sort_num: 0,
            memo: ''
          }
        ]
      },
      rules: {
        name: [
          {required: true, message: '动态功能设定名称不能为空', trigger: 'blur'}
        ],
        meta_name: [
          {required: true, message: '关联的元数据表不能为空', trigger: 'blur'}
        ],
        search_desc: [
          {required: true, message: '查询条件描述不能为空', trigger: 'blur'}
        ],
        column_name: [
          {required: true, message: '栏位名称不能为空', trigger: 'blur'}
        ],
        columnName: [
          {required: true, message: '栏位名称不能为空', trigger: 'blur'}
        ],
        eventsName: [
          {required: true, message: '普通事件的名称不能为空', trigger: 'change'}
        ],
        rowEventsName: [
          {required: true, message: '行事件的名称不能为空', trigger: 'change'}
        ]
      }
    }
  },
  created () {
    this.getAllFun()
    this.getRefTable()
    this.getAllEvents()
  },
  methods: {
    // 获取所有动态功能列表
    getAllFun () {
      this.isEdit = false
      this.$get('/dynamicfunc').then(data => {
        let dataResult = data.data.result
        if (dataResult.length) {
          // 默认选择第一个模板
          if (!this.currentFun || this.operationType === 'add') {
            this.currentFun = dataResult[0]
          } else {
            dataResult.forEach(val => {
              if (val.uid === this.currentFun.uid) {
                this.currentFun = val
              }
            })
          }
          // 右侧显示选中表的信息
          this.showFunInfo(this.currentFun.uid)
        }
        this.totalFun = dataResult
        this.filterFun = dataResult
      }).catch(error => {
        console.log(error)
      })
    },
    // 获取所有的元数据表
    getRefTable () {
      this.$get('/dynamicfunc/metalist').then(data => {
        if (data.status === 200) {
          this.totalRefTable = data.data.result
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 获取所有的事件资料-用于单表操作
    getAllEvents () {
      this.$get('/events/s_table').then(data => {
        let dataResult = data.data.result
        if (dataResult.code === 'failed') {
          this.$message({
            message: data.data.result.msg,
            type: 'warning'
          })
        } else if (dataResult.code === 'success') {
          this.totalEvents = {
            events: JSON.parse(JSON.stringify(dataResult.events)),
            row_events: JSON.parse(JSON.stringify(dataResult.row_events))
          }
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 获取选定关联表的栏位信息
    getRefColums () {
      if (this.ruleForm.meta_uid && this.totalRefTable.length) {
        this.totalRefTable.forEach(val => {
          if (val.metauid === this.ruleForm.meta_uid) {
            // 搜索的栏位信息
            this.searchColumnList = val.search_columns
            // 关联的栏位信息
            this.totalRefColumns = val.columns
          }
        })
      }
    },
    // 点击左边的动态功能时
    changeFun (item) {
      this.currentFun = item
      this.isEdit = false
      this.showFunInfo(item.uid)
    },
    // 获取指定动态功能的信息
    showFunInfo (funUid) {
      this.filterText = ''
      this.$refs.ruleForm.clearValidate()
      this.$get('/dynamicfunc/' + funUid).then(data => {
        if (data.data.result.code === 'failed') {
          this.$message({
            message: data.data.result.msg,
            type: 'warning'
          })
        } else if (data.data.result.code === 'success') {
          let dataInfo = data.data.result
          this.ruleForm.name = dataInfo.name
          this.ruleForm.desc = dataInfo.desc
          this.ruleForm.action_auth = dataInfo.action_auth
          this.ruleForm.meta_uid = dataInfo.meta_uid
          this.ruleForm.events = dataInfo.events
          this.ruleForm.rowEvents = dataInfo.row_events
          if (dataInfo.meta_uid) {
            this.ruleForm.meta_name = dataInfo.meta_desc + '(' + dataInfo.meta_name + ')'
            // 获取关联表的栏位信息
            this.getRefColums()
          } else {
            this.ruleForm.meta_name = ''
          }
          this.ruleForm.searchTable = dataInfo.search
          this.ruleForm.columTable = dataInfo.columns
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 生成动态功能菜单时
    getMeun () {
      if (this.ruleForm.meta_uid) {
        this.menuDialog = true
        this.functionObj = {
          funcName: this.ruleForm.name,
          funcAuth: this.ruleForm.action_auth,
          funcUid: this.currentFun.uid,
          from: 's_table'
        }
      } else {
        this.$message({
          message: '请先选择关联的元数据表,已完成功能菜单的设定',
          type: 'warning'
        })
      }
    },
    // 关闭了生成动态功能菜单时
    giveUpFunc () {
      this.menuDialog = false
    },
    // 点击新增动态功能的按钮
    addFun () {
      this.isEdit = false
      this.showAddDialog = true
    },
    // 新增功能成功时
    successAdd () {
      this.showAddDialog = false
      this.operationType = 'add'
      this.getAllFun()
    },
    // 新增功能失败时
    failedAdd () {
      this.showAddDialog = false
    },
    // 获取关联的元数据表时
    selectRefFun () {
      this.showRefDialog = true
    },
    // 选择关联表成功时
    sureSelectRef (fromSelect) {
      this.showRefDialog = false
      this.ruleForm.meta_name = fromSelect.metadesc + '(' + fromSelect.metaname + ')'
      this.ruleForm.meta_uid = fromSelect.metauid
      // 获取关联表的栏位信息
      this.getRefColums()
    },
    // 选择关联表失败时
    giveUpRef () {
      this.showRefDialog = false
    },
    // 点击删除时
    handleDeleteFun (funUid) {
      this.$confirm('此操作将永久删除该功能, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'el-button--info'
      }).then(() => {
        this.$delete('/dynamicfunc/' + funUid).then(data => {
          if (data.status === 204) {
            this.$message({
              message: '该报表模板已成功删除！',
              type: 'success'
            })
            this.operationType = 'add'
            this.getAllFun()
          } else {
            this.$message({
              message: '删除失败，请重试！',
              type: 'warning'
            })
          }
        }).catch(error => {
          console.log(error)
        })
      }).catch(() => {})
    },
    // 查询信息的表格
    // 表头的提示信息
    handelHelp (h, {column}) {
      if (column.labelClassName) {
        return (
          <el-tooltip effect="dark" placement="top">
            <div slot='content'>{column.labelClassName}</div>
            <span>{column.label}</span>
          </el-tooltip>
        )
      }
    },
    // 新增查询信息
    addSearchColumn () {
      if (this.ruleForm.meta_uid) {
        this.ruleForm.searchTable.push({
          search_id: '',
          search_desc: '',
          tips: '',
          is_required: false,
          memo: '',
          sort_num: 0,
          conditions: []
        })
      } else {
        this.$message({
          message: '请先选择关联的元数据表',
          type: 'warning'
        })
      }
    },
    // 新增查询条件的子条件时
    handleAddSearch (index, row) {
      this.searchList = row.conditions
      this.showAddSearchDialog = true
      this.clickRow = index
    },
    // 新增查询条件的子条件成功时
    successSearch (fromSelect) {
      this.showAddSearchDialog = false
      this.ruleForm.searchTable[this.clickRow].conditions = fromSelect
    },
    // 新增查询条件的子条件失败时
    giveUpSearch () {
      this.showAddSearchDialog = false
    },
    // 删除一条查询信息
    handleDeleteSearch (index) {
      this.$confirm('此操作将永久删除该查询信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'el-button--info'
      }).then(() => {
        this.ruleForm.searchTable.splice(index, 1)
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      }).catch(() => {})
    },
    // 新增栏位信息
    addColumn () {
      if (this.ruleForm.meta_uid) {
        this.ruleForm.columTable.push({
          column_name: '',
          column_desc: '',
          max_length: '',
          tips: '',
          check_required: false,
          check_regex: '',
          sort_num: 0,
          memo: ''
        })
      } else {
        this.$message({
          message: '请先选择关联的元数据表',
          type: 'warning'
        })
      }
    },
    // 删除一条栏位信息
    handleDeleteCloumn (index) {
      this.$confirm('此操作将永久删除该栏位, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'el-button--info'
      }).then(() => {
        this.ruleForm.columTable.splice(index, 1)
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      }).catch(() => {})
    },
    // 新增事件信息
    addEventsColumn (arrayName) {
      if (this.ruleForm.meta_uid) {
        this.ruleForm[arrayName].push({
          name: '',
          no: '',
          category: '',
          type: '',
          at: '',
          desc: ''
        })
      } else {
        this.$message({
          message: '请先选择关联的元数据表',
          type: 'warning'
        })
      }
    },
    // 删除事件信息
    handleDeleteEvents (index, arrayName) {
      this.$confirm('此操作将永久删除事件信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'el-button--info'
      }).then(() => {
        this.ruleForm[arrayName].splice(index, 1)
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      }).catch(() => {})
    },
    // 当选择的事件改变时
    changeEvents (rowIndex, arrayName) {
      let optionsList = []
      if (arrayName === 'events') {
        optionsList = this.totalEvents.events
      } else {
        optionsList = this.totalEvents.row_events
      }
      if (this.ruleForm[arrayName][rowIndex].no && optionsList.length) {
        optionsList.forEach(val => {
          if (val.no === this.ruleForm[arrayName][rowIndex].no) {
            this.ruleForm[arrayName][rowIndex] = val
          }
        })
      } else {
        this.ruleForm[arrayName][rowIndex] = {
          name: '',
          no: '',
          category: '',
          type: '',
          at: '',
          desc: ''
        }
      }
    },
    // 当鼠标聚集到选框时
    getEventList (arrayName, row) {
      let totalEventsArray = []
      if (arrayName === 'events') {
        totalEventsArray = JSON.parse(JSON.stringify(this.totalEvents.events))
        this.eventsList = []
      } else {
        totalEventsArray = JSON.parse(JSON.stringify(this.totalEvents.row_events))
        this.rowEventsList = []
      }
      if (totalEventsArray.length) {
        totalEventsArray.forEach(tVal => {
          let surePush = true
          this.ruleForm[arrayName].forEach(val => {
            if (val.no === tVal.no && row.no !== val.no) {
              surePush = false
            }
          })
          if (surePush) {
            if (arrayName === 'events') {
              this.eventsList.push(tVal)
            } else {
              this.rowEventsList.push(tVal)
            }
          }
        })
      }
    },
    // 选择栏位字段时
    columnSelect (row) {
      this.refTableColumns = []
      this.totalRefColumns.forEach(totalVal => {
        let surePush = true
        this.ruleForm.columTable.forEach(val => {
          if (val.column_name === totalVal.column_name && row.column_name !== val.column_name) {
            surePush = false
          }
        })
        if (surePush) {
          this.refTableColumns.push(totalVal)
        }
      })
    },
    // 选择栏位字段改变时
    columnSelectChange (row, rowIndex) {
      this.refTableColumns.forEach(val => {
        if (row.column_name === val.column_name) {
          this.ruleForm.columTable[rowIndex].column_desc = val.column_desc
        }
      })
    },
    // 点击编辑按钮时
    handleEditFun (item) {
      this.isEdit = true
      this.operationType = 'edit'
      this.currentFun = item
      this.showFunInfo(item.uid)
    },
    // 提交编辑的方法
    submitEdit () {
      let editData = {
        'name': this.ruleForm.name,
        'desc': this.ruleForm.desc,
        'action_auth': this.ruleForm.action_auth,
        'meta_uid': this.ruleForm.meta_uid,
        'search': this.ruleForm.searchTable,
        'columns': this.ruleForm.columTable,
        'events': this.ruleForm.events,
        'row_events': this.ruleForm.rowEvents
      }
      this.$patch('/dynamicfunc/' + this.currentFun.uid, {
        data: btoa(encodeURIComponent(JSON.stringify(editData)))
      }).then(data => {
        if (data.data.result.code === 'failed') {
          this.$message({
            message: data.data.result.msg,
            type: 'warning'
          })
        } else if (data.data.result.code === 'success') {
          this.$message({
            message: '动态功能编辑成功',
            type: 'success'
          })
          this.getAllFun()
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 点击取消按钮时
    resetForm (forms) {
      this.$refs[forms].resetFields()
      this.getAllFun()
    },
    // 点击确定提交的按钮时
    submitForm (forms) {
      this.$refs[forms].validate((valid) => {
        if (valid) {
          this.submitEdit()
        } else {
          return false
        }
      })
    }
  },
  watch: {
    // 左侧的检索
    filterText: {
      handler: function (val, oldVal) {
        // 当检索的内容为空时需要将表格的内容还原
        if (this.$trim(val) === '') {
          this.filterFun = this.totalFun
        } else {
          // 检索结果的数据存放在 this.filterFun 中
          this.filterFun = []
          // 所有的数据进行循环
          this.totalFun.forEach((value) => {
            // 进行检索匹配
            if (value.name.toString().indexOf(this.filterText) !== -1) {
              this.filterFun.push(value)
            }
          })
        }
      },
      deep: true
    }
  },
  components: {
    VTitle,
    VAdd,
    VRefTable,
    VSearchItem,
    VMenu
  }
}
